#include "UnitModels.h"

#include <fstream>

#include "json/json.h"

namespace VectorTD
{
	GameRenderer::GameMesh* LoadUnitModel(const char* p_modelPath)
	{
		GameRenderer::GameMesh* result = NULL;
		std::string line("");
		std::string file("");
		std::ifstream myfile(p_modelPath);
		if(myfile.is_open())
		{
			while (myfile.good())
			{
				getline(myfile,line);
				file += line;
				file += "\n";
			}
			myfile.close();
		}
		else
			LOG("Error while opening file: %s\n", p_modelPath);

		Json::Value root;
		Json::Reader reader;
		bool parsedSuccess = reader.parse(file, root, false);
		if(parsedSuccess)
		{
			LOG("Unit model json parsed successfull: %s\n", p_modelPath);

			const Json::Value shape = root["shape"];
			LOG("shape number of coordinate: %d\n", shape.size());

			ASSERT(shape.size() % 2 == 0, "A point must be defined by an X an Y value (no Z). Number of coordinate should be pair: %d", shape.size());

			std::vector<GameRenderer::MeshPoint> shapePoints(shape.size()/2);

			for(unsigned int i = 0 ; i < shape.size() ; i+=2)
			{
				LOG("Shape point(%lf, %lf)\n", shape[i].asDouble(), shape[i+1].asDouble());
				shapePoints[i/2] = GameRenderer::MeshPoint(static_cast<GLfloat>(shape[i].asDouble()), static_cast<GLfloat>(shape[i+1].asDouble()), 0.0f);
			}

			GameRenderer& gr = GameRenderer::GetInstance();
			result = gr.CreateMesh(shapePoints, GameRenderer::SHADER_SIMPLE_TRANSFORM_COLOR, true, 0.15f);
		}
		return result;
	}
}

